import { useState, useRef, useEffect } from "react";
import _ from "lodash";

function ASon({ onGetMsg }) {
  const msg = "111111111111111";
  return (
    <div>
      <span>{msg}</span>
      <button onClick={() => onGetMsg(msg)}>打印A</button>
    </div>
  );
}

function BSon({ message }) {
  return (
    <div>
      <span>{message}</span>
    </div>
  );
}

function App() {
  const list = [
    {
      name: "周杰伦",
      content: "11111111",
      time: "2023-10-11",
      like: 999,
    },
    {
      name: "林俊杰",
      content: "22222222",
      time: "2023-10-12",
      like: 888,
    },
    {
      name: "汪苏泷",
      content: "3333333",
      time: "2023-10-13",
      like: 666,
    },
  ];
  const tab = [
    {
      label: "最新",
      value: "new",
    },
    {
      label: "最热",
      value: "hot",
    },
  ];
  const [comlist, setComlist] = useState(_.orderBy(list, "time", "desc"));
  const onDel = (item) => {
    setComlist(comlist.filter((v) => v.name != item.name));
  };
  const [cur, setCur] = useState("new");
  const onTab = (item) => {
    setCur(item.value);
    setComlist(
      _.orderBy(comlist, item.value == "new" ? "time" : "like", "desc")
    );
  };
  const [content, setContent] = useState("");
  const inputRef = useRef(null);
  const onOpen = () => {
    setComlist([
      {
        name: "周杰伦",
        content,
        time: "2023-10-11",
        like: 999,
      },
      ...comlist,
    ]);
    setContent("");
    inputRef.current.focus();
  };
  const [message, setMsg] = useState("2");
  function getMsg(msg) {
    setMsg(msg);
  }
  const [num,setNum] = useState(0)
  useEffect(() => {
    const getName = () => {
      setTimeout(() => {
        console.log(num);
        setNum(num + 1)
      }, 3000);
    };
    getName()
  }, [num]);

  return (
    <div className="App">
      <div className="header">
        <ASon onGetMsg={getMsg} />
        <BSon message={message} />
        <input
          ref={inputRef}
          value={content}
          onChange={(e) => setContent(e.target.value)}
        ></input>
        <button onClick={onOpen}>发布</button>
      </div>
      <div className="tabs">
        {tab.map((item, index) => (
          <span
            className={cur == item.value ? "active" : ""}
            key={index}
            onClick={() => onTab(item)}
          >
            <span>{item.label}</span>
            {tab.length - 1 != index && <span>|</span>}
          </span>
        ))}
      </div>
      {comlist.map((item, index) => (
        <div key={index} className="list">
          <div className="name">{item.name}</div>
          <div className="content">{item.content}</div>
          <div className="time">
            <span>{item.time}</span>
            <button onClick={() => onDel(item)}>删除</button>
          </div>
          <hr />
        </div>
      ))}
    </div>
  );
}

export default App;
